package com.calligraphy.order.service.impl;

import com.calligraphy.order.model.Cart;
import com.calligraphy.order.service.CartService;
import com.calligraphy.order.utils.JsonUtils;

import com.calligraphy.order.interceptor.LoginInterceptor;
import com.calligraphy.product.client.ProductClient;
import com.calligraphy.product.common.ProductInfoOutput;
import com.calligraphy.user.common.UserOutput;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author hy
 * @Date 2019/1/23 20:11
 **/
@Service
public class CartServiceImpl implements CartService {

    private static final String KEY_PREFIX = "calligraphy:cart:uid";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductClient productClient;

    @Override
    public void addCart(Cart cart) {
        UserOutput userOutput = LoginInterceptor.getLoginUser();
        String key = KEY_PREFIX + userOutput.getEmail();
        BoundHashOperations<String,Object,Object> hashOperations = this.stringRedisTemplate.boundHashOps(key);
        String productId = cart.getProductId();
        Integer num = cart.getNum();
        Boolean result = hashOperations.hasKey(productId);
        if (result){
            //5.存在，获取购物车数据
            String json = hashOperations.get(productId).toString();
            cart = JsonUtils.parse(json,Cart.class);
            //6.修改购物车数量
            cart.setNum(cart.getNum() + num);
        }else{
            //7.不存在，新增购物车数据
            cart.setUserId(userOutput.getEmail());
            //8.其他商品信息，需要查询商品微服务
            ProductInfoOutput productInfoOutput = productClient.findOne(productId);
            cart.setImage(StringUtils.isBlank(
                    productInfoOutput.getProductIcon()) ? "" : StringUtils.split(productInfoOutput.getProductIcon(),
                    ",")[0]);
            cart.setPrice(productInfoOutput.getProductPrice());
            cart.setProductName(productInfoOutput.getProductName());
            cart.setOwnSpec(productInfoOutput.getProductDescription());
        }
        //9.将购物车数据写入redis
        hashOperations.put(cart.getProductId(),JsonUtils.serialize(cart));

    }

    @Override
    public List<Cart> queryCartList() {
        UserOutput userOutput = LoginInterceptor.getLoginUser();
        String key = KEY_PREFIX + userOutput.getEmail();
        if (!this.stringRedisTemplate.hasKey(key)) {
            //不存在直接返回
            return null;
        }
        BoundHashOperations<String,Object,Object> hashOperations = this.stringRedisTemplate.boundHashOps(key);
        List<Object> carts = hashOperations.values();
        //判断是否有数据
        if (CollectionUtils.isEmpty(carts)){
            return null;
        }
        //查询购物车数据
        return carts.stream().map( o -> JsonUtils.parse(o.toString(),Cart.class)).collect(Collectors.toList());
    }

    @Override
    public void updateNum(String productId, Integer num) {
        UserOutput userOutput = LoginInterceptor.getLoginUser();
        String key = KEY_PREFIX + userOutput.getEmail();
        BoundHashOperations<String,Object,Object> hashOperations = this.stringRedisTemplate.boundHashOps(key);
        //获取购物车
        String json = hashOperations.get(productId).toString();
        Cart cart = JsonUtils.parse(json,Cart.class);
        cart.setNum(num);
        //写入购物车
        hashOperations.put(productId,JsonUtils.serialize(cart));
    }

    @Override
    public void deleteCart(String productId) {
        UserOutput userOutput = LoginInterceptor.getLoginUser();
        String key = KEY_PREFIX + userOutput.getEmail();
        BoundHashOperations<String,Object,Object> hashOperations = this.stringRedisTemplate.boundHashOps(key);
        //删除商品
        hashOperations.delete(productId);
    }
}
